<template>
  <div class="loginDialog">
    <el-dialog v-model="props.showLogin" :show-close="false" class="dialogBody" :before-close="close" destroy-on-close draggable>
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <el-tabs v-model="activeNav" class="headerTabs" @tab-click="handleNav">
            <el-tab-pane :label="t('login.memberLogin')" name="login"></el-tab-pane>
            <el-tab-pane :label="t('login.oneRegister')" name="register"></el-tab-pane>
            <el-tab-pane :label="t('login.forgetPwd')" name="forget"></el-tab-pane>
          </el-tabs>

          <el-button class="headerClose" type="warning" circle @click="close">
            <el-icon ><div class="iconfont icon guanbi"></div></el-icon>
          </el-button>

        </div>
      </template>
      <div class="dialogBody">
        <div class="loginBody" v-if="activeNav=='login'">
          <el-form
            ref="loginFormRef"
            style="max-width: 600px"
            :model="loginForm"
            :rules="loginRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="t('login.mobile')+'：'"
              prop="mobile"
            >
              <el-input
                v-model.number="loginForm.mobile"
                type="text"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.pwd')+'：'"
              prop="password"
            >
              <el-input
                v-model="loginForm.password"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.captchaCode')+'：'"
              prop="imgCode"
            >
              <el-input class="imgCodeBox"
                v-model="loginForm.imgCode"
                type="text"
                autocomplete="off"
              >
                <template #append>
                  <el-image id="image-code" style="width: 150px; height: 50px" alt="验证码" fit="contain" v-on:click="loadImageCode()" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item v-if="showNewReg">
                <el-divider content-position="right">{{ newRegToast }}</el-divider>
            </el-form-item>
            
          </el-form>
        </div>
        <div class="registerBody" v-if="activeNav=='register'">
          <el-form
            ref="regFormRef"
            style="max-width: 600px"
            :model="regForm"
            :rules="regRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="t('login.mobile')+'：'"
              prop="mobile"
            >
              <el-input
                v-model.number="regForm.mobile"
                type="text"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.nickName')+'：'"
              prop="nickName"
            >
              <el-input
                v-model="regForm.nickName"
                type="text"
                autocomplete="off"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="forgetBody" v-if="activeNav=='forget'">
          <el-form
            ref="forgetFormRef"
            style="max-width: 600px"
            :model="forgetForm"
            :rules="forgetRules"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item
              :label="t('login.mobile')+'：'"
              prop="mobile"
            >
              <el-input
                v-model.number="forgetForm.mobile"
                type="text"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.smsCode')+'：'"
              prop="shortMessageCode"
            >
              <el-input
                v-model="forgetForm.shortMessageCode"
                type="text"
                autocomplete="off"
              >
                <template #append>
                  <el-button @click="SMSTime(true)" :disabled="btnText!='发送短信验证码' && btnText!='Send Message Code'?true:false">{{ btnText }}</el-button>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item
              :label="t('login.pwd')+'：'"
              prop="passwordOriginal"
            >
              <el-input
                v-model="forgetForm.passwordOriginal"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

            <el-form-item
              :label="t('login.pwdConf')+'：'"
              prop="passwordConfirm"
            >
              <el-input
                v-model="forgetForm.passwordConfirm"
                type="password"
                autocomplete="off"
              />
            </el-form-item>

          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">{{ t('login.cancle') }}</el-button>
          <el-button @click="resetData(activeNav=='login'?loginFormRef:(activeNav=='register')?regFormRef:forgetFormRef)">{{ t('login.reset') }}</el-button>
          <el-button type="primary" @click="submitData(activeNav=='login'?loginFormRef:(activeNav=='register')?regFormRef:forgetFormRef,activeNav)">
            {{ activeNav=='login'?t('login.memberLogin'):(activeNav=='register'?t('login.oneRegister'):(activeNav=='forget'?t('login.submit'):t('login.submit'))) }}
          </el-button>
        </div>
      </template>
      
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
/** */
import {getCurrentInstance,ref,reactive,watch,computed,defineEmits} from 'vue'

import { FormInstance,FormRules,Action } from 'element-plus'
import {fileTrans} from '@/utils/fileTrans'

// import {useStore} from 'vuex'
import { useStore } from '@/store/index.ts'
const store=useStore()

//router引入
import {useRouter,useRoute} from 'vue-router'
const router=useRouter()
const route=useRoute()

//缓存引入
import {sessionCache,localCache} from '@/utils/cache'

import {useI18n} from 'vue-i18n'
const {t} = useI18n()

const {proxy}:any =getCurrentInstance()
//定义组件发射
const $emit=defineEmits<{
  (e:string,data:any):void
}>()

/***************引入组件变量**************/

import useForm from '@/entity/login/useForm';
const {titleId,
    titleClass,
    activeNav,
    localUser,
    loginForm,
    loginFormRef,
    loginRules,
    regForm,
    regFormRef,
    regRules,
    forgetForm,
    forgetFormRef,
    forgetRules}= useForm(t)
import useMethods from '@/entity/login/useMethods';

const {resetData,submitData,login,register,getCodeToken}
=useMethods(t,{loginForm,regForm,forgetForm},router)

//md5引入
import md5 from '@/utils/md5.js'

//接口引入
import api from '@/api/index'

let showNewReg:boolean=false

//监听
const props=defineProps({
  language:{
    type:String,
    default:'zh-cn'
  },
  showLogin:Boolean,
})

watch(()=>props.language,(newVal,oldVal)=>{
  console.log("newVal", newVal)
  console.log("oldVal", oldVal)
  console.log("languag",props.language)
})
//注意，watch里面使用的方法不能封装在ts中
watch(()=>props.showLogin,(newVal,oldVal)=>{
  console.log("open--",newVal)
  if(newVal){
    activeNav.value='login'
    countDown=61
    SMSTime(false)

    loadImageCode()
  }
})

/***********************监听store变化************************/
watch(()=>store.state.count,(newVal,oldVal)=>{
    console.log("count更新：",newVal," 旧count：",oldVal)
    if(store.state.loginUser!=null){
        $emit('loginSuccess',true)
        showNewReg=false
    }else{
        loadImageCode()
    }
    
})



watch(()=>store.state.registerMobile,(newVal,oldVal)=>{
    console.log("新注册电话：",newVal)
    activeNav.value='login'
    loginForm.mobile=newVal
    loginForm.password='c123456'
    showNewReg=true
    loadImageCode()
    console.log("loginForm===> ",loginForm)
  })


const newRegToast='新注册会员默认密码，请联系客服：0991-6232202'

function handleNav(e:any){
  activeNav.value=e.props.name
  if(activeNav.value=='login'){
    loadImageCode()
  }
  console.log("当前nav：",e.props.name,"activeNav: ",activeNav.value)
  
}

/**********忘记密码表单*******/

let countDown=61
const btnText=ref(props.language.name=='zh-cn'?'发送短信验证码':'Send Message Code')
let timer:any={}
const SMSTime=async (flag:any)=>{
  console.log("forgeForm: ",forgetForm.shortMessageCode)
  try{
    //主动校验
    const valid=await forgetFormRef.value?.validate()
    if(valid){
      console.log("通过")
      if(flag){
        countDown=60
        clearTimeout(timer)
      }
      console.log('countDown-------',countDown)
      if(countDown==0 || countDown==61){
        btnText.value=props.language.name=='zh-cn'?'发送短信验证码':'Send Message Code'
        return
      }else{
        countDown--
        btnText.value=countDown+ (props.language.name=='zh-cn'?' 后重新获取':' Seconds Retrieve It')
      }
      console.log("btnText: ",btnText)
      timer= setTimeout(()=>{
        SMSTime(false)
      },1000)
    }
  }catch(error){
    console.log("验证手机号异常：",error)
  }
  
}

const close=()=>{
  console.log("关闭模态框")
  $emit('resetLogin',false)
}

function open(){
  console.log("打开模态框----------")
  loadImageCode()
  // showLogin.value=true
}

function loadImageCode(){
  setTimeout(()=>{
    document.getElementById('image-code')?.setAttribute('src','http://39.104.21.39:8899/business/client/kaptcha/image-code/'+getCodeToken())
  })
}

//向父组件暴露方法
defineExpose({
  open
})

</script>

<style lang="scss" scoped>
@import '../assets/sass/index.scss';
@import '@/assets/sass/common.scss';
.loginDialog{
  ::v-deep(.el-dialog){
    width: 600px;
  }
  .imgCodeBox{
    ::v-deep(.el-input-group__append){
      width: 125px;
      height: 50px;
      padding: 0 !important;
    }
  }
  
}
.my-header{
  width:100%;
  display: flex;
  .headerTabs{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    ::v-deep(.el-tabs__header){
      width: 100%;
      display:flex;
    }
    ::v-deep(.el-tabs__nav-wrap){
      width: 100%;
      display:flex;
    }
    ::v-deep(.el-tabs__item){
      font-size: 18px;
    }
    ::v-deep(.is-active){
      font-weight: 700;
    }
  }
  .headerClose{
    position: absolute;
    right: 15px;
    top: 15px;
  }
  .image-code{
    
  }
}
</style>